package com.tree.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tree.backend.common.Result;
import com.tree.backend.entity.dto.UserDTO;
import com.tree.backend.entity.pojo.Company;
import com.tree.backend.entity.pojo.User;
import com.tree.backend.entity.vo.UserVO;
import com.tree.backend.service.ICompanyService;
import com.tree.backend.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping
@RestController
@RequiredArgsConstructor
public class AuthController {
    private final IUserService userService;
    private final ICompanyService companyService;


    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody UserDTO userDTO) {
        return userService.login(userDTO);
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody Company company) {
        boolean save = companyService.save(company);
        if (save) {
            Company one = companyService.getOne(
                    new LambdaQueryWrapper<Company>()
                            .eq(Company::getCompanyName, company.getCompanyName()));
            userService.save(User.builder()
                            .phone(company.getContactPhone())
                            .username(company.getContactPhone())
                            .password("123456")
                            .realName(company.getContactPhone())
                            .companyId(one.getId())
                            .status(0)
                            .userRole(1)
                    .build());
        }
        return Result.success("");
    }
}
